package cn.newtest.common.dbutils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.RowProcessor;

/**
 * 一个RowProcessor的实现
 * 
 * @author WangChui(baiyibing@gmail.com)
 * @version 1.0 TODO
 * 
 */
public class DbRowProcessor implements RowProcessor {
	private BeanProcessor convert = null;

	public BeanProcessor getConvert() {
		return convert;
	}

	public void setConvert(BeanProcessor convert) {
		this.convert = convert;
	}

	/**
	 * Convert a <code>ResultSet</code> row into an <code>Object[]</code>.
	 * This implementation copies column values into the array in the same order
	 * they're returned from the <code>ResultSet</code>. Array elements will
	 * be set to <code>null</code> if the column was SQL NULL.
	 * 
	 * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet)
	 */
	public Object[] toArray(ResultSet rs) throws SQLException {
		ResultSetMetaData meta = rs.getMetaData();
		int cols = meta.getColumnCount();
		Object[] result = new Object[cols];

		for (int i = 0; i < cols; i++) {
			result[i] = rs.getObject(i + 1);
		}

		return result;
	}

	public Map toMap(ResultSet rs) throws SQLException {
		DbRow result = new DbRow();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cols = rsmd.getColumnCount();

		for (int i = 1; i <= cols; i++) {
			result.put(rsmd.getColumnName(i), rs.getObject(i));
		}
		return result;
	}

	/**
	 * Convert a <code>ResultSet</code> row into a JavaBean. This
	 * implementation delegates to a BeanProcessor instance.
	 * 
	 * @see org.apache.commons.dbutils.BeanProcessor#toBean(java.sql.ResultSet,
	 *      java.lang.Class)
	 * @see org.apache.commons.dbutils.RowProcessor#toBean(java.sql.ResultSet,
	 *      java.lang.Class)
	 */
	public Object toBean(ResultSet rs, Class type) throws SQLException {
		return this.convert.toBean(rs, type);
	}

	/**
	 * Convert a <code>ResultSet</code> into a <code>List</code> of
	 * JavaBeans. This implementation delegates to a BeanProcessor instance.
	 * 
	 * @see org.apache.commons.dbutils.BeanProcessor#toBeanList(java.sql.ResultSet,
	 *      java.lang.Class)
	 * @see org.apache.commons.dbutils.RowProcessor#toBeanList(java.sql.ResultSet,
	 *      java.lang.Class)
	 */
	public List toBeanList(ResultSet rs, Class type) throws SQLException {
		return this.convert.toBeanList(rs, type);
	}

}